﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Summer.Model.Common;

namespace Summer.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        public IConfiguration _configuration;
        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        public string GetJwtToken(UserInfo user)
        {
            var claims = new Claim[]
                        {
                            new Claim(ClaimTypes.Name,user.UserName),
                            new Claim(ClaimTypes.Role,user.Role)
                        };
            JwtSettings setting = _configuration.GetSection("JwtSettings") as JwtSettings;
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                setting.Issuer,
                setting.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(30),
                creds);

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return jwtToken;
        }
    }
}